﻿using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using CodeLibrary.IO.Utils;

namespace CodeLibrary.Controls.PropertyGrid.PropertyGridEditors
{
    public class OpenFileEditorAttribute : Attribute
    {
        public OpenFileEditorAttribute(string filter)
        {
           Filter = filter;
        }

        public string Filter { get; set; }
    }

    public class OpenFileEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            var edSvc = (IWindowsFormsEditorService) provider.GetService(typeof (IWindowsFormsEditorService));
            if (edSvc != null)
            {
                var oAttr =
                    (OpenFileEditorAttribute) (context.PropertyDescriptor.Attributes[typeof (OpenFileEditorAttribute)]);
                if (oAttr != null)
                    value = FileUtils.SelectFile(oAttr.Filter, (string) value);
                else
                    value = FileUtils.SelectFile("所有文件|*.*");
            }
            return value ?? "";
        }
    }
}